package com.zheng.business.web.controller;

import com.zheng.business.common.constant.BusinessConstant;
import com.zheng.business.common.constant.BusinessResult;
import com.zheng.business.common.constant.BusinessResultConstant;
import com.zheng.business.dao.model.BusinessAgentBillLog;
import com.zheng.business.dao.model.BusinessAgentBillLogExample;
import com.zheng.business.dao.model.BusinessAgentBillStatistics;
import com.zheng.business.dao.model.BusinessAgentBillStatisticsExample;
import com.zheng.business.rpc.api.BusinessAgentBillLogService;
import com.zheng.business.rpc.api.BusinessAgentBillStatisticsService;
import com.zheng.common.base.BaseController;
import com.zheng.common.constant.Constant;
import com.zheng.common.util.PropertiesUtil;
import com.zheng.common.util.RedisUtil;
import com.zheng.upms.rpc.api.UpmsApiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author lvg EMIAL：<a href="mailto:weiguo.liang@gh-ca.com">weiguo.liang@gh-ca.com</a> <br>
 * @version 1.0 <br>
 * @Company: GH-CA<br>
 * @ClassName: BusinessAgentBillLogController <br>
 * @Description: 提现管理 <br>
 * @date 2019/10/15 15:37<br>
 **/
@Controller
@RequestMapping("/manage/billlog")
@Api(value = "提现申请控制器", description = "提现申请控制器")
public class BusinessAgentBillLogController extends BaseController {

    @Autowired
    BusinessAgentBillLogService businessAgentBillLogService;

    @Autowired
    BusinessAgentBillStatisticsService businessAgentBillStatisticsService;

    @Autowired
    UpmsApiService upmsApiService;

    @ApiOperation(value = "提现申请首页")
    @RequiresPermissions("business:billlog:read")
    @RequestMapping(value = "/index", method = {RequestMethod.GET, RequestMethod.POST})
    public String index(ModelMap modelMap) {
        return "/manage/billlog/index.jsp";
    }

    @ApiOperation(value = "提现申请列表")
    @RequiresPermissions("business:billlog:read")
    @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object list(
                       @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
                       @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
                       @RequestParam(required = false, value = "sort") String sort,
                       @RequestParam(required = false, value = "order") String order,
                       @RequestParam(required = false, value = "status") Integer status
                       ) {

        String loginUserName = this.getLoginUserName();
        Integer upmsAgentId = upmsApiService.selectUserAgentIdByUsername(loginUserName);

        BusinessAgentBillLogExample example = new BusinessAgentBillLogExample();
        BusinessAgentBillLogExample.Criteria criteria = example.createCriteria();


        if(!upmsAgentId.equals(Constant.BJS_AGENT_ID)){
            criteria.andAgentIdEqualTo(upmsAgentId);
        }

        if(status != null && status != -1){
            criteria.andStatusEqualTo(status);
        }
        List<BusinessAgentBillLog> rows = businessAgentBillLogService.selectByExampleForOffsetPage(example, offset, limit);
        long total = businessAgentBillLogService.countByExample(example);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }

    @ApiOperation(value = "处理提现账单中")
    @RequiresPermissions("business:billlog:confirm")
    @RequestMapping(value = "/confirm/{id}", method = {RequestMethod.GET, RequestMethod.POST})
    public Object confirm(@PathVariable("id") int id ) {
         BusinessAgentBillLog log = businessAgentBillLogService.selectByPrimaryKey(id);
         if(log.getStatus().equals(BusinessConstant.BillStatus.APPLY.getValue())){
                log.setStatus(BusinessConstant.BillStatus.PROCESSING.getValue());
                businessAgentBillLogService.updateByPrimaryKeySelective(log);
         }else{
             return new BusinessResult(BusinessResultConstant.FAILED,"账单申请已被处理。");
         }

        return new BusinessResult(BusinessResultConstant.SUCCESS,"已确认。");
    }

    @ApiOperation(value = "提现撤销")
    @RequiresPermissions("business:billlog:cancel")
    @RequestMapping(value = "/cancel/{id}", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object cancel(@PathVariable("id") int id ) {
        BusinessAgentBillLog log = businessAgentBillLogService.selectByPrimaryKey(id);
        if(log.getStatus().equals(BusinessConstant.BillStatus.APPLY.getValue())){
            log.setStatus(BusinessConstant.BillStatus.CANCEL.getValue());
            businessAgentBillLogService.updateByPrimaryKeySelective(log);
        }else{
            return new BusinessResult(BusinessResultConstant.FAILED,"申请单不是申请状态，已不可撤销。");
        }

        return new BusinessResult(BusinessResultConstant.SUCCESS,"已撤销。");
    }


    @ApiOperation(value = "获取图片")
    @RequiresPermissions("business:billlog:read")
    @RequestMapping(value = "/loadImage/{fileName}", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public void loadImage(@PathVariable("fileName") String fileName,
                          HttpServletRequest request, HttpServletResponse response) throws IOException {
        if(StringUtils.isNotBlank(fileName)) {
            String path = PropertiesUtil.getInstance().getValue(BusinessConstant.UPLOAD_FILE_PATH) + "billlog";
            FileInputStream ips = null;
            OutputStream out = null;
            try {
                //获取图片存放路径
                File file = new File(path + "/" + fileName);
                String prefix = fileName.substring(fileName.lastIndexOf("."));
                ips = new FileInputStream(file);
                out = response.getOutputStream();
                response.setContentType("image/" + prefix);
                //读取文件流
                int len = 0;
                byte[] buffer = new byte[1024 * 10];
                while ((len = ips.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                out.close();
                ips.close();
            }
        }
    }

    @ApiOperation(value = "上传图片")
    @RequiresPermissions("business:billlog:submit")
    @RequestMapping(value = "/upload/{id}", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object upload(@PathVariable("id") int id,@RequestParam(value = "file") MultipartFile file) throws IOException {
        String path = PropertiesUtil.getInstance().getValue(BusinessConstant.UPLOAD_FILE_PATH) + "billlog";
        File f = new File(path);
        if (!f.exists())
            f.mkdirs();
        String name = file.getOriginalFilename();
        String prefix = name.substring(name.lastIndexOf("."));
        String fileName = UUID.randomUUID() + prefix;
        f = new File(path + "/" + fileName);
        if (!f.exists()) {
            f.createNewFile();
            file.transferTo(f);
        }
        RedisUtil.set(id+"",fileName,120);
        return new BusinessResult(BusinessResultConstant.SUCCESS,fileName);
    }

    @ApiOperation(value = "账单明细")
    @RequiresPermissions("business:billlog:submit")
    @RequestMapping(value = "/submit/{id}", method = {RequestMethod.GET})
    public String detail(@PathVariable("id") int id, ModelMap modelMap) {
        BusinessAgentBillLog log = businessAgentBillLogService.selectByPrimaryKey(id);
        modelMap.put("log", log);
        return "/manage/billlog/submit.jsp";
    }

    @ApiOperation(value = "提交提现申请结果")
    @RequiresPermissions("business:billlog:submit")
    @RequestMapping(value = "/submit", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object submit(
            BusinessAgentBillLog businessAgentBillLog
            ) throws IOException {
        try{
            BusinessAgentBillLog log = businessAgentBillLogService.selectByPrimaryKey(businessAgentBillLog.getId());
            if(log.getStatus().equals(BusinessConstant.BillStatus.PROCESSING.getValue())){

                BusinessAgentBillStatisticsExample example = new BusinessAgentBillStatisticsExample();
                example.createCriteria().andAgentIdEqualTo(log.getAgentId());
                BusinessAgentBillStatistics statistics = businessAgentBillStatisticsService.selectFirstByExample(example);
                statistics.setAmountRemainder(statistics.getAmountRemainder().subtract(log.getAmount()));
                businessAgentBillStatisticsService.updateByPrimaryKeySelective(statistics);
                businessAgentBillLogService.updateByPrimaryKeySelective(businessAgentBillLog);

                return new BusinessResult(BusinessResultConstant.SUCCESS,"提交成功。");
            } else {
                return new BusinessResult(BusinessResultConstant.FAILED,"状态不正确。");
            }


        } catch (Exception e){
            return new BusinessResult(BusinessResultConstant.FAILED,"提交失败。");
        }
    }

}
